package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j


public class ReportServiceImpl implements ReportService {

    //营业额统计
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //日期列表
        List<LocalDate> list=new ArrayList<>();//将开始时间到结束时间的日期都添加到这个集合中

        list.add(begin);
        while (!begin.equals(end))//将
        {
            begin=begin.plusDays(1);//每次加一天,一直加到end这一天
            list.add(begin);
        }

        //根据时间查 查询营业额
        List<Double> TurnOverList =new ArrayList<>();
        //select sum(amount) from order where order_time > begin and order_time < end and status = 5
        for (LocalDate date : list) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//每一天的开始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//每一天的结束时间
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);

            Double turnOver=orderMapper.getTurnOver(map);//获取当天的营业额
            //细节turnOver中的一个元素加入存在null的话就会将这个null拼进字符串
            turnOver=turnOver==null?0.0:turnOver;

            TurnOverList.add(turnOver);
        }


        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list,","))//将这个集合转换成字符串 封装到对象中
                .turnoverList(StringUtils.join(TurnOverList,","))//集合转成字符串
                .build();
    }

    //用户统计
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> datelist=new ArrayList<>();//将开始时间到结束时间的日期都添加到这个集合中
        datelist.add(begin);
        while (!begin.equals(end))//将
        {
            begin=begin.plusDays(1);//每次加一天,一直加到end这一天
            datelist.add(begin);
        }
        //根据创建时间来判断用户的新增情况
        //新增用户 select count(id) from user where create_time > ? and create_time < ? ;
        List<Integer> newUserlist =new ArrayList<>();
        //总用户 select count(id) from user where create_time < ?
        List<Integer> totoalUserlist=new ArrayList<>();

        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();
            map.put("end",endTime);
            Integer totalUser=userMapper.getUserAtatistics(map);
            totoalUserlist.add(totalUser);

            map.put("begin",beginTime);
            Integer newUser=userMapper.getUserAtatistics(map);
            newUserlist.add(newUser);

        }



        return UserReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .newUserList(StringUtils.join(newUserlist,","))
                .totalUserList(StringUtils.join(totoalUserlist,","))
                .build();
    }

    //订单统计
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end))
        {
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //订单总数列表
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> orderValidList=new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //每天的订单总数 select count(id) from orders where create_time > ? and create_time < ?
            Integer countOrder = getCountOrder(beginTime, endTime, null);
            orderCountList.add(countOrder);

            //每天的订单有效数select count(id) from orders where create_time > > and create_time < ? and status= 5
            Integer validOrder = getCountOrder(beginTime, endTime, Orders.COMPLETED);
            orderValidList.add(validOrder);

        }



        //总订单数
        Integer allCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer ValidCount = orderValidList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(allCount!=0)
        {
            orderCompletionRate=ValidCount.doubleValue()/allCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .validOrderCountList(StringUtils.join(orderValidList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(allCount)
                .validOrderCount(ValidCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list=orderMapper.getSalesTop10(beginTime,endTime);//这个集合中的goods对象装有name和数量属性

        //通过循环或者strem流提取出来
        //商品名称集合
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //数量集合
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    //导出excel文件
    @Override
    public void exportExcel(HttpServletResponse response) {
        //1.获取数据   时间前30天到昨天结束
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2.通过poi写入模板
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("tamplate/运营数据报表模板.xlsx");
        //基于原有的模板文件创建一个新的excel文件

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据
            XSSFSheet sheet1 = excel.getSheet("sheet1");

            //获取行
            sheet1.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);

            //获取第四行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行
            row= sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                 begin = begin.plusDays(1);
                //这是每一天的数据
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
                //获取行
                row=sheet1.getRow(7+i);//从表格的第八行进行填充,逐渐增加
                row.getCell(1).setCellValue(begin.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }


            //3.通过输出流下载到客户端浏览器

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    private Integer getCountOrder(LocalDateTime begin,LocalDateTime end, Integer status)
    {
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        Integer count=orderMapper.getCountByMap(map);//这是查询每天的订单(总数/有效订单数)
        return count;
    }

}
